package com.example.Web_chat.controller;

import com.example.Web_chat.mapper.GroupChatMapper;
import com.example.Web_chat.mapper.GroupChatMemberMapper;
import com.example.Web_chat.mapper.GroupMessageMapper;
import com.example.Web_chat.mapper.UserMapper;
import com.example.Web_chat.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/group")
public class GroupController {
    @Autowired
    private GroupChatMapper groupChatMapper;

    @Autowired
    private GroupChatMemberMapper groupChatMemberMapper;
//
    @Autowired
    private GroupMessageMapper messageMapperGroup;

    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    private  UserMapper userMapper;


    @PostMapping("/create")
    public Object createGroup(@RequestBody GroupMessageRequest request) {
        // 创建群聊
        GroupChat groupChat = new GroupChat();
        groupChat.setGroupName(request.getGroupName());
        groupChat.setCreatorId(request.getSenderId());
        groupChat.setCreatedAt(LocalDateTime.now());

        groupChatMapper.createGroup(groupChat);

        // 将创建者添加为群聊成员
        List<Integer> memberIds = request.getMemberIds();
        for (Integer memberId : memberIds) {
            GroupChatMember member = new GroupChatMember();
            member.setGroupId(groupChat.getGroupId());
            member.setUserId(memberId);
            member.setJoinedAt(LocalDateTime.now());
            groupChatMemberMapper.addMember(member);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("groupId", groupChat.getGroupId());
        result.put("groupName", groupChat.getGroupName());
        return result;
    }
    @PostMapping("/join")
    public R joinGroup(@RequestBody GroupMessageRequest request) {

        // 检查群聊是否存在
        GroupChat groupChat = groupChatMapper.findById(request.getGroupId());
        if (groupChat == null) {
            return R.fail("群聊不存在");
        }
        GroupChatMember existing = groupChatMemberMapper.findByGroupIdAndUserId(
                request.getGroupId(), request.getSenderId()
        );
        if (existing != null) {
            return R.fail("用户已在群聊中");
        }
        // 添加成员到群聊
        GroupChatMember member = new GroupChatMember();
        member.setGroupId(request.getGroupId());
        member.setUserId(request.getSenderId());
        member.setJoinedAt(LocalDateTime.now());

        groupChatMemberMapper.addMember(member);

        return R.ok();
    }

    // 发送消息
//    @PostMapping("/sendMessage")
//    public String sendMessage(@RequestBody GroupMessageRequest request) {
//        GroupMessage message = new GroupMessage();
//        message.setGroupId(request.getGroupId());
//        message.setSenderId(request.getSenderId());
//        message.setMessageContent(request.getMessageContent());
//        message.setTimestamp(LocalDateTime.now());
//
//        // 保存到数据库
//        messageMapperGroup.sendMessageGroup(message);
//
//        // ✅ 查询发送者用户名
//        User sender = userMapper.selectByID(request.getSenderId());
//        String fromName = sender != null ? sender.getUsername() : "未知用户";
//
//        // ✅ 构造完整消息结构
//        Map<String, Object> msg = new HashMap<>();
//        msg.put("type", "groupMessage");
//        msg.put("groupId", request.getGroupId());
//        msg.put("fromId", request.getSenderId());
//        msg.put("fromName", fromName);  // ✅ 必须加这个字段
//        msg.put("content", request.getMessageContent());
//
//        // ✅ 转为 JSON 字符串
//        String jsonMessage = "";
//        try {
//            jsonMessage = objectMapper.writeValueAsString(msg);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        // ✅ 广播
//        List<WebSocketSession> sessions = getSessionsByGroupId(request.getGroupId());
//        for (WebSocketSession session : sessions) {
//            if (session.isOpen()) {
//                try {
//                    session.sendMessage(new TextMessage(jsonMessage));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//        return "消息已发送";
//    }
    //返回指定群的历史消息。
    @GetMapping("/messages")
    public List<GroupMessage> getGroupMessages(@RequestParam Integer groupId) {
        List<GroupMessage> list = messageMapperGroup.findByGroupId(groupId);
        List<GroupMessage> result = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            GroupMessage groupMessage = list.get(i);
            User user = userMapper.selectByID(groupMessage.getSenderId());
            groupMessage.setFromName(user.getUsername());
            result.add(groupMessage);
        }
        return result;
    }


    @GetMapping("/list")
    public List<Map<String, Object>> listUserGroups(@RequestParam Integer userId) {
        List<GroupChat> groups = groupChatMapper.findGroupsByUserId(userId);
        List<Map<String, Object>> result = new ArrayList<>();
        for (GroupChat group : groups) {
            Map<String, Object> groupInfo = new HashMap<>();
            groupInfo.put("groupId", group.getGroupId());
            groupInfo.put("groupName", group.getGroupName());
            result.add(groupInfo);
        }
        return result;
    }


    // 删除群聊
    @PostMapping("/delete")
    public Map<String, Object> exitGroup(@RequestBody Map<String, Integer> request) {
        Integer groupId = request.get("groupId");
        Integer userId = request.get("userId");

        Map<String, Object> result = new HashMap<>();

        // 检查群聊是否存在
        GroupChat group = groupChatMapper.findById(groupId);
        if (group == null) {
            result.put("success", false);
            result.put("message", "群聊不存在");
            return result;
        }

        // 从群成员中移除用户
        int deleted = groupChatMemberMapper.deleteMember(groupId, userId);
        if (deleted > 0) {
            result.put("success", true);
            result.put("message", "已成功退出群聊");
        } else {
            result.put("success", false);
            result.put("message", "退出失败，用户可能不在群聊中");
        }

        return result;
    }


}
